<template>
  <div>
    <!-- 面包屑部分 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <!-- 添加角色按钮 -->
      <el-row>
        <el-col>
          <el-button
            type="primary"
            @click="openAddRoleDialog">添加角色</el-button>
        </el-col>
      </el-row>
      <!-- 表格部分 -->
      <el-table
        :data="rolesList"
        border
        stripe>
        <!-- 展开部分 -->
        <el-table-column type="expand">
          <template v-slot="value">
            <el-row
              v-for="(value1, index1) in value.row.children"
              :key="value1.id + index1"
              :class="[ index1 === 0 ? 'bd-top' : '', 'bd-bottom', 'v-center' ]">
              <!-- tag标签 -->
              <el-col :span="6">
                <!-- 一级标签 -->
                <el-tag
                  closable
                  @close="removeRightById(value.row, value1.id)">
                    {{ value1.authName }}
                </el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <el-col :span="18">
                <el-row
                  v-for="(value2, index2) in value1.children"
                  :key="value2.id + index2"
                  :class="[ index2 === 0 ? '' : 'bd-top', 'v-center' ]">
                  <el-col :span="8">
                    <!-- 二级标签 -->
                    <el-tag closable type="success">{{ value2.authName }}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="16">
                    <!-- 三级标签 -->
                    <el-tag
                      closable
                      type="warning"
                      v-for="(value3, index3) in value2.children"
                      :key="value3.id + index3">
                        {{ value3.authName }}
                      </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index"/>
        <el-table-column label="角色名称" prop="roleName" min-width="100px"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc" min-width="200px"></el-table-column>
        <el-table-column label="操作" min-width="290px">
          <template v-slot="value">
            <!-- 编辑 -->
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-edit"
              @click="openEditRoleDialog(value.row)">编辑</el-button>
            <!-- 删除 -->
            <el-button
              size="mini"
              type="danger"
              icon="el-icon-delete"
              @click="removeRole(value.row.id)">删除</el-button>
            <!-- 分配权限 -->
            <el-button
              size="mini"
              type="warning"
              icon="el-icon-setting"
              @click="openSetRightsDialog(value.row)">
                分配权限
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 分配权限的dialog -->
    <el-dialog
      title="提示"
      :visible.sync="isShowSetRightsDialog"
      width="50%"
      @close="closeSetRightsDialog">
      <el-tree
        show-checkbox
        node-key="id"
        ref="treeRef"
        :data="rightsList"
        :props="treeProps"
        :default-expanded-keys="showTreeExpand"
        :default-checked-keys="showTreeRights">
      </el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isShowSetRightsDialog = false">取 消</el-button>
        <el-button type="primary" @click="confirmChangeRoles">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑角色 -->
    <el-dialog
      title="编辑角色"
      :visible.sync="editRoleDialogVisible"
      width="50%"
      @close="closeEditRoleDialog">
      <el-form
        :model="editRoleForm"
        :rules="editRoleFormRules"
        label-width="100px"
        label-position="right"
        ref="editRoleFormRef">
        <el-form-item label="角色名称:" prop="roleName">
          <el-input
            v-model="editRoleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述:">
          <el-input
            v-model="editRoleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="editRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitEditRole">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 添加角色 -->
    <el-dialog
      title="编辑角色"
      :visible.sync="addRoleDialogVisible"
      width="50%"
      @close="closeAddRoleDialog">
      <el-form
        :model="addRoleForm"
        :rules="addRoleFormRules"
        label-width="100px"
        label-position="right"
        ref="addRoleFormRef">
        <el-form-item label="角色名称:" prop="roleName">
          <el-input
            v-model="addRoleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述:">
          <el-input
            v-model="addRoleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="addRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitAddRole">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'PowerRoles',
  data () {
    return {
      // 角色列表
      rolesList: [],
      // 权限列表
      rightsList: [],
      // 是否展示分配权限的对话框
      isShowSetRightsDialog: false,
      // 展示tree对应的key
      treeProps: {
        label: 'authName',
        children: 'children'
      },
      // 默认tree的展开情况
      showTreeExpand: [],
      // 默认已选的权限
      showTreeRights: [],
      // 分配权限时候的id
      roleId: '',
      // 编辑角色对话框是否出现
      editRoleDialogVisible: false,
      // 编辑角色表单
      editRoleForm: {
        roleName: '',
        roleDesc: '',
        id: ''
      },
      // 编辑角色表单规则
      editRoleFormRules: {
        roleName: [
          { required: true, message: '角色名称不能为空', trigger: 'blur' }
        ]
      },
      // 添加角色表单
      addRoleForm: {
        roleName: '',
        roleDesc: ''
      },
      // 添加表单的规则
      addRoleFormRules: {
        roleName: [
          { required: true, message: '角色姓名不能为空', trigger: 'blur' }
        ]
      },
      // 控制添加角色对话框是否显示
      addRoleDialogVisible: false
    }
  },
  created () {
    // 初始化数据
    this.getRolesList()
  },
  methods: {
    // 1. 获取角色列表
    async getRolesList () {
      const { data: res } = await this.$http.get('/roles')
      // 状态码
      const status = res.meta.status
      // console.log(res)
      if (status !== 200) {
        return this.$message.error('获取角色列表失败.')
      } else if (status === 200) {
        this.rolesList = res.data
      }
    },
    // 2. 获取权限列表
    async getRightsList (type = 'list') {
      const { data: res } = await this.$http.get('/rights/' + type)
      // 状态码
      const status = res.meta.status
      if (status === 200) {
        console.log(res)
        this.rightsList = res.data
      } else if (status !== 200) {
        return this.$message.error('获取权限列表失败')
      }
    },
    // 3. 删除角色权限tag标签
    async removeRightById (role, rightId) {
      const result = await this.$confirm('删除权限操作不可逆转, 确定此操作码?', '提示', {
        type: 'warning'
      }).catch(err => err)
      if (result === 'confirm') {
        const { data: res } = await this.$http.delete(`/roles/${role.id}/rights/${rightId}`)
        // 状态码
        const status = res.meta.status
        if (status === 200) {
          this.$message.success('删除权限成功!')
          return (role.children = res.data)
        } else {
          return this.$message.error('删除权限失败.')
        }
      } else {
        this.$message.info('已取消删除权限操作')
      }
    },
    // 4. 点击分配权限按钮大考dialog
    openSetRightsDialog (role) {
      // 显示dialog
      this.roleId = role.id
      this.getRightsList('tree')
      // 遍历一级标签
      // console.log(role)

      // for (const value1 of role.children) {
      //   this.showRightsLevel1.push(value1.id)
      //   if (value1.children) {
      //     // 遍历二级标签
      //     for (const value2 of value1.children) {
      //       this.showRightsLevel2.push(value2.id)
      //       if (value2.children) {
      //         // 遍历三级标签
      //         for (const value3 of value2.children) {
      //           this.showRightsLevel3.push(value3.id)
      //         }
      //       }
      //     }
      //   }
      // }
      // 递归
      this.getTreeKeys(role)

      this.isShowSetRightsDialog = true
    },
    // 递归
    getTreeKeys (node) {
      if (!node.children) {
        // 显示的子权限
        return this.showTreeRights.push(node.id)
      } else {
        // 默认的展开
        this.showTreeExpand.push(node.id)
      }
      node.children.forEach(value => {
        this.getTreeKeys(value)
      })
    },
    // 5. 确认修改权限
    async confirmChangeRoles () {
      const rolesIdStr = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ].join(',')
      console.log(rolesIdStr)
      const { data: res } = await this.$http.post(`/roles/${this.roleId}/rights`, { rids: rolesIdStr })
      if (res.meta.status !== 200) {
        this.$message.error('分配权限失败.')
      } else {
        this.$message.success('分配权限成功!')
      }

      // 重置showRightsLevel

      // 关闭对话框
      this.isShowSetRightsDialog = false
      this.getRolesList()
    },
    // 6. 关闭对话框执行的功能
    closeSetRightsDialog () {
      this.showTreeExpand = []
      this.showTreeRights = []
      this.roleId = ''
      // this.rightsList = []
    },
    // 7. 删除角色
    async removeRole (id) {
      const result = await this.$confirm('提确定要删除吗', '提示', {
        type: 'warning'
      }).catch(err => err)
      if (result !== 'confirm') {
        return this.$message.info('已取消删除操作')
      }
      // confirm
      const { data: res } = await this.$http.delete(`roles/${id}`)
      if (res.meta.status !== 200) {
        return this.$message.error('删除角色出错')
      }
      console.log(res)
      // 删除成功
      this.$message.success('删除角色成功')
      this.getRolesList()
    },
    // 8. 编辑角色对话框关闭
    closeEditRoleDialog () {
      this.editRoleForm.id = ''
      this.editRoleForm.roleName = ''
      this.editRoleForm.roleDesc = ''
    },
    // 9. 打开编辑角色对话框
    openEditRoleDialog (data) {
      this.editRoleForm.roleName = data.roleName
      this.editRoleForm.roleDesc = data.roleDesc
      this.editRoleForm.id = data.id
      this.editRoleDialogVisible = true
    },
    // 10. 确认编辑角色
    submitEditRole () {
      this.$refs.editRoleFormRef.validate(async valid => {
        if (!valid) return this.$message.error('请填写角色名称')
        const { data: res } = await this.$http.put(`/roles/${this.editRoleForm.id}`, this.editRoleForm)
        console.log(res)
        if (res.meta.status !== 200) {
          return this.$message.error('编辑角色信息错误')
        }
        // 修改成功
        this.$message.success('编辑角色信息成功')
        // 重新获取
        this.getRolesList()
        this.editRoleDialogVisible = false
      })
    },
    // 11. 添加角色对话框关闭
    closeAddRoleDialog () {
      this.$refs.addRoleFormRef.resetFields()
      this.addRoleForm.roleName = ''
      this.addRoleForm.roleDesc = ''
    },
    // 12. 打开添加角色对话框
    openAddRoleDialog () {
      this.addRoleDialogVisible = true
    },
    // 13. 确认添加角色
    submitAddRole () {
      this.$refs.addRoleFormRef.validate(async valid => {
        if (!valid) return this.$message.error('请填写正确信息')
        const { data: res } = await this.$http.post('/roles', this.addRoleForm)
        if (res.meta.status !== 201) {
          return this.$message.error('角色创建失败')
        }
        // 角色创建成功
        this.$message.success('角色创建成功')
        // 关闭对话框 并 刷新列表
        this.getRolesList()
        this.addRoleDialogVisible = false
      })
    }
  }
}
</script>

<style scoped lang="less">
.el-tag {
  margin: 7px;
}
.el-breadcrumb {
  font-size: 12px;
}
.el-card {
  margin-top: 15px;
  min-width: 1070px;
}
.v-center {
  display: flex;
  align-items: center;
}
.bd-top {
  border-top: 1px solid #eee;
}
.bd-bottom {
  border-bottom: 1px solid #eee;
}
.el-table {
  margin-top: 15px;
}
</style>
